package org.ydsw.data.manage.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;

public class GetPostReqUtils {
    public static Long sendReq(String urlFree) {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            HttpGet httpGetFree = new HttpGet(urlFree);
            client = HttpClients.createDefault();
            response = client.execute(httpGetFree);
            HttpEntity entityFree = response.getEntity();
            String resultFree = EntityUtils.toString(entityFree);
            JSONArray jsonObjectFree1 = JSONObject.parseObject(resultFree).getJSONObject("data").getJSONArray("result");
            JSONArray jsonObjectFree = JSONObject.parseObject(jsonObjectFree1.get(0).toString()).getJSONArray("value");
            Long filesystemSizeFree = Long.parseLong(jsonObjectFree.get(1).toString()) / 1024 / 1024 / 1024;
            return filesystemSizeFree;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static float getUsedSizePercent(String total, String free) {
        float used = 0f;
        float v = 0f;
        Long totalL = sendReq(total);
        Long freeL = sendReq(free);
        System.out.println("总空间"+totalL);
        System.out.println("剩余空间"+freeL);
        if (totalL != null && freeL != null) {
            used = totalL - freeL;
            NumberFormat numberFormat2 = NumberFormat.getInstance();
            numberFormat2.setMaximumFractionDigits(2);
            String percentResult = numberFormat2.format(used);
            String percentResults = percentResult.replaceAll(",", "");
            used = Float.parseFloat(percentResults);
            v = used / totalL;
            String percentResult2 = numberFormat2.format(v);
            String percentResults2 = percentResult2.replaceAll(",", "");
            v = Float.parseFloat(percentResults2);
        }
        return v;
    }



    public static String sendPost(String url, JSONObject jsonObject, String encoding) throws IOException {
        String body = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        response.close();
        //json.parse这一步的原因是，返回的json字符创是Unicode编码格式，需要通过json.parse解析成中文格式并h返回
        return String.valueOf(JSON.parse(body));
    }


    public static String doPut(String url, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
//        httpPut.setHeader("token", token);

        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static String doGet(String requesturl){
        StringBuffer buffer=new StringBuffer();
        try {
            URL url=new URL(requesturl);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();

            //获得返回值
            InputStream inputStream=httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

            //将bufferedReader值放到str里
            String str=null;
            while ((str=bufferedReader.readLine())!=null){
                buffer.append(str);
            }

            //关闭输入流和bufferReader
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            //断开连接
            httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
